package com.sunday.common.statemachine.study.e4_Hierarchical;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Scanner;
import java.util.UUID;


@Slf4j
@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Autowired
    private StateMachine<OrderStates, OrderEvents> stateMachine;

    @Override
    public void run(String... args) throws Exception {

        while (true) {
            Scanner scan = new Scanner(System.in);//实例化Scanner对象
            String input = scan.nextLine();//接受用户输入的字符串
            // 判断用户输入是否为"exit"
            if ("exit".equalsIgnoreCase(input)) {
                log.info("程序已退出");
                break;
            } else {
                log.info("你输入的文本是: {}", input);
                try {
                    Mono<Message<OrderEvents>> mono = Mono.just(MessageBuilder
                            .withPayload(OrderEvents.valueOf(input.toUpperCase()))
                            .setHeader("OrderId", UUID.randomUUID())
                            .setHeader("stockAvailable", true)
//                            .setHeader(StateMachineMessageHeaders.HEADER_DO_ACTION_TIMEOUT, 5000)
                            .build());

                    // org.springframework.statemachine.ObjectStateMachine
//                    stateMachine.sendEvent(OrderEvents.valueOf(input.toUpperCase()));
                    stateMachine.sendEvent(mono).subscribe();
                } catch (Exception e) {
                    log.error("无法识别的事件: {} , 异常: {}", input, e.toString());
                }
            }

        }

    }
}
